import axios from 'axios';
import type { ApiResponse } from '../auth/types';

// 用户信息接口类型
export interface UserInfo {
  user_id: number;
  username: string;
  nickname: string;
  gender: string;
  phone: string;
  email: string;
  avatar: string;
  status: number;
  description: string;
  artboardCount: number;
  followerCount: number;
  attentionCount: number;
  created_at: string;
  updated_at: string;
}

// 创建axios实例
const userApi = axios.create({
  baseURL: import.meta.env.VITE_BASE_API+"/api/v1",
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 请求拦截器
userApi.interceptors.request.use(
  config => {
    const token = localStorage.getItem('access_token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器
userApi.interceptors.response.use(
  response => response,
  error => {
    if (error.response) {
      // 处理401未授权的情况
      if (error.response.status === 401) {
        localStorage.removeItem('access_token');
        localStorage.removeItem('token_expires_at');
        window.location.href = '/login';
      }
    }
    return Promise.reject(error);
  }
);

// 获取用户信息
export const getUserInfo = async (): Promise<ApiResponse<UserInfo>> => {
  try {
    const response = await userApi.get<ApiResponse<UserInfo>>('/users/me');
    return response.data;
  } catch (error) {
    throw error;
  }
};

// 上传头像
export const uploadAvatar = async (file: File): Promise<ApiResponse> => {
  const formData = new FormData();
  formData.append('avatar', file);
  
  return userApi.post('/users/me/avatar', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  });
};

// 用户作品集接口类型
export interface UserBoard {
  id: number;
  title: string;
  category_id: number;
  tags: string;
  status: number;
  hot_ness: number;
  flag: number;
  description: string;
  images: {
    id: number;
    title: string;
    content: string;
    user_id: number;
    img_url: string;
    views_count: number;
    download_count: number;
    created_at: number;
  }[];
}

// 获取用户作品集
export const getUserBoards = async (): Promise<ApiResponse<UserBoard[]>> => {
  const response = await userApi.get('/users/me/boards');
  return response.data;
};